﻿using System.IO;
using System.Text;

namespace Jayden.Dll.Core.Logging
{
	public class StreamHandler : Handler
	{
		private Stream m_Stream;

		public StreamHandler() { }
		public StreamHandler(Stream stream, Formatter formatter)
		{
			m_Stream = stream;
			Formatter = formatter;
		}

		public Stream Stream { get { return m_Stream; } set { m_Stream = value; } }

		public override void Close() { if (m_Stream != null) m_Stream.Close(); m_Stream = null; }

		public override void Flush() { if(m_Stream != null) m_Stream.Flush(); }

		public override void Publish(LogRecord record)
		{
			if (m_Stream == null)
				return;
			string messageFormatted = Formatter.FormatMessage(record);
			byte[] bytes = Encoding.GetBytes(messageFormatted);
			lock (m_Stream)
			{
				m_Stream.Write(bytes, 0, bytes.Length);
			}
		}
	}
}
